<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Operation\Service\Common;

use Admin\Data\Common;
use Doctrine\ORM\EntityManager;
use Operation\Entity\CouponCodeRule;
use Sales\Entity\OrderDiscountRecord;

class CouponCode
{
    public static function couponCodeCalculation($goodsCart, $data, $couponCodeStr, EntityManager $entityManager, $translator)
    {
        $couponCode = $entityManager->getRepository(\Operation\Entity\CouponCode::class)->findOneBy(['couponCodeStr' => $couponCodeStr]);
        if ($couponCode == null || $couponCode->getOrderId() > 0) return ['discountCost' => 0, 'errorMessage' => $translator->translate('该优惠码不存在或者已经被使用。')];

        $couponCodeRule = $entityManager->getRepository(CouponCodeRule::class)->findOneBy(['couponCodeRuleId' => $couponCode->getCouponCodeRuleId(), 'couponCodeState' => 1]);
        if ($couponCodeRule == null) return ['discountCost' => 0, 'errorMessage' => $translator->translate('该优惠码已经被关闭，不能被使用。')];

        if (!Common::checkTime($couponCodeRule->getCouponCodeStartTime(), $couponCodeRule->getCouponCodeEndTime())) return ['discountCost' => 0, 'errorMessage' => $translator->translate('该优惠码不在可使用的有效期内。')];
        if (!Common::checkUser($data['userGroupId'], $couponCodeRule->getCouponCodeUserType(), unserialize($couponCodeRule->getCouponCodeUserGroup()))) return ['discountCost' => 0, 'errorMessage' => $translator->translate('您所在的会员组，不能使用该优惠码。')];

        if ($couponCodeRule->getUserUseNum() > 0) {
            $userBuyUseNum = $entityManager->getRepository(OrderDiscountRecord::class)->count(['userId' => $data['userId'], 'discountType' => 'couponCode', 'id' => $couponCodeRule->getCouponCodeRuleId()]);
            if ($userBuyUseNum >= $couponCodeRule->getUserUseNum()) return ['discountCost' => 0, 'errorMessage' => $translator->translate('优惠码使用个数已到极限，不能再次使用')];
        }

        $costTotal = self::cartCostTotal($goodsCart, $couponCodeRule);

        $discountCost = 0;
        $discountId   = 0;
        if ($costTotal >= $couponCodeRule->getShoppingAmount()) {
            $discountCost   = $couponCodeRule->getShoppingDiscount();
            $discountId     = $couponCodeRule->getCouponCodeRuleId();
        }

        return ['discountCost' => $discountCost, 'discountTitle' => $translator->translate('优惠码优惠'), 'discountType' => 'couponCode', 'discountId' => $discountId, 'couponCode' => $couponCodeStr, 'couponCodeId' => $couponCode->getCouponCodeId()];
    }

    /**
     * 购物车过滤符合条件的商品，并计算总金额
     * @param $goodsCart
     * @param CouponCodeRule $couponCodeRule
     * @return int|mixed
     */
    private static function cartCostTotal($goodsCart, CouponCodeRule $couponCodeRule)
    {
        $costTotal = 0;
        foreach ($goodsCart as $goodsValue) {
            if (Common::checkGoods($goodsValue['classId'], $couponCodeRule->getCouponCodeGoodsType(), unserialize($couponCodeRule->getCouponCodeGoodsBody()), $goodsValue['brandId'])) {
                $costTotal = $costTotal + $goodsValue['goodsAmount'];
            }
        }

        return $costTotal > 0 ? Common::calculation($costTotal, 1, '*', 2) : 0;
    }
}